package org.farm2.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.farm2.auth.domain.Post;
import org.farm2.auth.dto.MenusDto;
import org.farm2.auth.service.ActionsServiceInter;
import org.farm2.auth.service.PostServiceInter;
import org.farm2.base.domain.FarmUserContext;
import org.farm2.files.domain.ResourceFile;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.luser.domain.LocalOrg;
import org.farm2.luser.domain.LocalUser;
import org.farm2.luser.service.LocalOrgServiceInter;
import org.farm2.luser.service.LocalUserServiceInter;
import org.farm2.service.inter.FarmUserServiceInter;
import org.farm2.service.inter.WebResourceServiceInter;
import org.farm2.skc.utils.SkcFileMarkUtils;
import org.farm2.tools.db.commons.FarmUUID;
import org.farm2.tools.web.Farm2HtmlUtils;
import org.farm2.tools.web.Farm2HttpUtils;
import org.farm2.tools.web.domain.WebDoc;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用戶信息读取的实现类，将来可以替换为第三方实现
 */
@Component
@Slf4j
public class WebResourceService implements WebResourceServiceInter {
    @Autowired
    private LocalUserServiceInter localUserServiceImpl;
    @Autowired
    private LocalOrgServiceInter localOrgServiceImpl;
    @Autowired
    private PostServiceInter postServiceImpl;
    @Autowired
    private ActionsServiceInter actionsServiceImpl;
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;

    @Override
    public WebDoc downloadWebPage(String url) {
        WebDoc doc = Farm2HttpUtils.getWebPageByUrl(url);
        Document document = Jsoup.parse(doc.getHtml());
        for (Element img : document.getElementsByTag("img")) {
            try {
                String src = Farm2HtmlUtils.getSrc(img);
                if (StringUtils.isNotBlank(src)) {
                    String eurl = Farm2HttpUtils.getImgUrl(src, doc.getBaseUrl());
                    String nsrc = downLoadImg(eurl);
                    img.attr("src", SkcFileMarkUtils.FARM2_BASEPATH_FLAG + nsrc);
                    img.removeAttr("data-src");
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        doc.setHtml(document.html());
        return doc;
    }

    public String downLoadImg(String eurl) throws IOException {

        log.info("html img from:" + eurl);

        Map<String, Object> backObj = new HashMap<>();
        backObj.put("webUrl", eurl);
        String exname = null;
        try {
            if (eurl.lastIndexOf("?") > 0) {
                exname = eurl.substring(0, eurl.lastIndexOf("?"));
            } else {
                exname = eurl;
            }
            if (eurl.lastIndexOf(".") > 0) {
                exname = exname.substring(exname.lastIndexOf(".") + 1);
            } else {
                exname = eurl;
            }
            if (exname == null || exname.length() > 10) {
                exname = "gif";
            }
        } catch (Exception e) {
            exname = "gif";
        }
        try {
            try {

                eurl = encodeChinese(eurl, "utf-8");
            } catch (Exception e) {
                throw e;
            }
            URL innerurl = new URL(eurl);

            HttpURLConnection connection = (HttpURLConnection) innerurl.openConnection();
            connection.setRequestProperty("User-Agent", Farm2HttpUtils.getAgent());
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(5 * 1000);

            InputStream input = null;
            OutputStream fos = null;
            ResourceFile rfile = null;
            try {
                input = connection.getInputStream();
                if (!exname.toUpperCase().equals("PNG") && !exname.toUpperCase().equals("JPG") && !exname.toUpperCase().equals("JPEG") && !exname.toUpperCase().equals("GIF")) {
                    exname = "jpg";
                }
                rfile = resourceFileServiceImpl.creatNullFile(FarmUUID.getUUID32() + "." + exname);
                fos = new FileOutputStream(resourceFileServiceImpl.getFilePath(rfile).getFile());

                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = input.read(buffer, 0, 8192)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
            } finally {
                if (input != null) {
                    input.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }

            eurl = "api/files/download/" + rfile.getId();
            return eurl;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 对url中的中文编码
     *
     * @param url
     * @param chartSet
     * @return
     */
    public static String encodeChinese(String url, String chartSet) {
        try {
            Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
            while (matcher.find()) {
                String tmp = matcher.group();
                url = url.replaceAll(tmp, java.net.URLEncoder.encode(tmp, chartSet));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }
}
